package com.ht.WeNas.utils;

import com.ht.WeNas.data.dto.FbData;
import lombok.NonNull;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class FileAccessUtils {
    public static List<FbData> listFiles(Path root) {
        if (root == null) {
            return List.of();
        }
        if (!Files.isDirectory(root)) {
            return null;
        }
        List<FbData> res = new ArrayList<>();
        try {
            Files.walkFileTree(root, new FileVisitor<>() {
                List<Path> files = new ArrayList<>();
                
                @Override
                @NonNull
                public FileVisitResult preVisitDirectory(Path dir, @NonNull BasicFileAttributes attrs) throws IOException {
                    files = new ArrayList<>();
                    return FileVisitResult.CONTINUE;
                }

                @Override
                @NonNull
                public FileVisitResult visitFile(Path file, @NonNull BasicFileAttributes attrs) throws IOException {
                    files.add(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                @NonNull
                public FileVisitResult visitFileFailed(Path file, @NonNull IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                @NonNull
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    // 忽略空文件夹
                    if (files.isEmpty()) {
                        return FileVisitResult.CONTINUE;
                    }

                    // 对当前文件夹的文件进行自然排序
                    List<Path> orderedList = files.stream().sorted(MyPathUtil.getNaturalComparator()).toList();
                    res.add(new FbData(dir, orderedList));
                    files = new ArrayList<>();
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return res;
    }
}
